package com.xsf.jieyou.business.oauth2;

import com.xsf.jieyou.business.common.dto.ResponseResult;
import com.xsf.jieyou.business.common.dto.ResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义认证异常类
 * <p>
 * Description:自定义 oAuth2 错误反馈
 * </p>
 *
 * @author xsf
 * @version v1.0.0
 * @date 2019/11/16 0016 19:21
 **/
@Slf4j
@Component("authExceptionEntryPoint")
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        Map<String, Object> map = new HashMap<String, Object>();
        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            // 状态码
            Integer code = null;
            // 消息
            String message = null;
            // 1、没有令牌
            if (cause == null) {
                code = ResponseStatus.NONE_TOKEN.code();
                message = ResponseStatus.NONE_TOKEN.message();
            }
            // 2、无效 Token
            else if (cause instanceof InvalidTokenException) {
                code = ResponseStatus.INVALID_TOKEN.code();
                message = ResponseStatus.INVALID_TOKEN.message();
            }
            // 3、其他
            else {
                code = ResponseStatus.SERVICE_NOT_FOUND.code();
                message = ResponseStatus.SERVICE_NOT_FOUND.message();
            }
            response.getWriter().write(ResponseResult.build(code, message).toJsonString());

            log.warn("\n[全局业务异常]\r\n异常处理类：{}\r\n异常编码：{}\n异常消息：{}\r\n异常记录：{}",
                    this.getClass().getName(), code, message, cause);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
